<?php

namespace app\api\service;

use app\common\model\Detailed;
use app\common\model\Order;
use app\common\model\Product;
use app\common\model\SampleOrder;
use app\common\model\User;
use app\common\model\UserAddress;
use app\common\model\UserAmount;
use app\common\service\CommonWechatPayService;
use app\Response;
use think\facade\Cache;
use think\facade\Db;
use think\response\Json;

class SampleOrderService
{
    /*** 样品订单列表
     * @param $user_id 用户ID
     * @param $page int 页码
     * @param $num int 个数
     * @param $state int 订单状态
     * @return array
    */
    public static function sampleOrderListService($user_id,$page,$num,$state){
        $where[] = ["o.enable","=",1];
        $where[] = ["o.uid","=",$user_id];
        if(!empty($state)||is_numeric($state)){
            $where[] = ["o.state","=",$state];
        }
        $list = SampleOrder::sampleOrderList($where,$page,$num,"o.*,p.img");
        if(!empty($list)){
            $data = $list->toArray();
            foreach ($data as $k => $v){
                $data[$k]["addtime"] = !empty($v["addtime"])?date("Y-m-d H:i:s",$v["addtime"]):"";
            }
            $count = SampleOrder::sampleOrderListCount($where);
        }else{
            $data = [];
            $count = 0;
        }
        return Response::wrapData($data,$count);
    }

    /*** 订单详情
     * @param $id int
     * @param $user_id int
     * @return Json
    */
    public static function sampleOrderInfoService(int $id, int $user_id){
        $userInfo = User::userInfo(["uid"=>$user_id]);
        if($userInfo['type'] != 23){
            return Response::wrapError(0,"账户非达人用户!");
        }
        if($userInfo['enable'] == 0){
            return Response::wrapError(-200,"此账户已被禁用,如有疑问请联系平台客服!");
        }
        $info = SampleOrder::dataInfo(["uid"=>$user_id,"id"=>$id,"enable"=>1]);


        if(empty($info)){
            return Response::wrapError(0,"未检测到当前订单信息!");
        }
        $p_info = Product::dataInfo(["id"=>$info["p_id"]]);
        $info["address"] = !empty($info["address"])?json_decode($info["address"]):"";
        if(!empty($p_info)){
            $info["p_info"] = $p_info;
            $info["addtime"] = !empty($info["addtime"])?date("Y-m-d H:i:s",$info["addtime"]):"";
            $info["paytime"] = !empty($info["paytime"])?date("Y-m-d H:i:s",$info["paytime"]):"";
            $info["sendtime"] = !empty($info["sendtime"])?date("Y-m-d H:i:s",$info["sendtime"]):"";
            $info["endtime"] = !empty($info["endtime"])?date("Y-m-d H:i:s",$info["endtime"]):"";
        }else{
            $info["p_info"] = [];
        }
        return Response::wrapData($info);
    }



    /** 下单
     * @param $data array 下单参数
     * @return json
     */
    public static function robSampleOrderService($data,$user_id){
        $userInfo = User::userInfo(["uid"=>$user_id]);
        if($userInfo['type'] != 23){
            return Response::wrapError(0,"账户非达人用户!");
        }
        if($userInfo['enable'] == 0){
            return Response::wrapError(-200,"此账户已被禁用,如有疑问请联系平台客服!");
        }
        if(!isset($data["a_id"])||empty($data["a_id"])){
            return Response::wrapError(0,"请选择收货地址!");
        }
        $address = UserAddress::addressInfo(["id"=>$data["a_id"],"uid"=>$user_id]);
        if (empty($address)){
            return Response::wrapError(0,"地址信息获取异常!");
        }
        $p_info = Product::dataInfo(["id"=>$data["id"]]);
        if(empty($p_info)){
            return Response::wrapError(0,"商品信息异常!");
        }
        $order_data = [
            "uid" => $user_id,
            "u_type" => $userInfo['type'],
            "p_id" => $data["id"],
            "p_name" => $p_info["p_name"],
            "p_num" => $p_info["p_num"],
            "sup_price" => $p_info["supply_price"],
            "order_quantity" => $data["num"],
            "low_price" => bcmul($p_info["supply_price"],$data["num"],2),
            "o_pro_num" => self::createOrderNumber(),
            "state" => 0,
            "addtime" => time(),
            "address" => $address->toArray()
        ];
        $res = SampleOrder::addInfo($order_data)['id'];
        if($res){
            return Response::wrapData($res);
        }else{
            return Response::wrapError(0,"下单操作失败");
        }
    }

    /*** 样品订单支付
     * @param $id 订单ID
    */
    public static function sampleOrderWxPayService($id,$user_id){
        $userInfo = User::userInfo(["uid"=>$user_id]);
        if($userInfo['type'] != 23){
            return Response::wrapError(0,"账户非达人用户!");
        }
        if($userInfo['enable'] == 0){
            return Response::wrapError(-200,"此账户已被禁用,如有疑问请联系平台客服!");
        }
        if(empty($userInfo["open_id"])){
            return Response::wrapError(-1,"请先授权绑定微信!");
        }
        $oInfo = SampleOrder::dataInfo(["id"=>$id,"uid"=>$user_id]);
        if(empty($oInfo)){
            return Response::wrapError(0,"订单信息异常！");
        }
        if($oInfo["state"] > 0){
            return Response::wrapError(0,"该订单不在可支付状态!");
        }
//        Db::startTrans();//开启事务
//        try {
//
//            Db::commit();
//        } catch (\Exception $e) {
//            Db::rollback();
//        }
        $orderPayInfo = CommonWechatPayService::orderPayData($user_id,$userInfo["open_id"],$oInfo["low_price"],$oInfo["o_pro_num"]);
        if(!empty($orderPayInfo)){
            return Response::wrapData($orderPayInfo);
        }else{
            return Response::wrapError(0,"请稍后重试!");
        }

    }


    public static function robSampleOrderEditService($user_id,$id,$state){
        $userInfo = User::userInfo(["uid"=>$user_id]);
        if($userInfo['type'] != 23){
            return Response::wrapError(0,"账户非达人用户!");
        }
        if($userInfo['enable'] == 0){
            return Response::wrapError(-200,"此账户已被禁用,如有疑问请联系平台客服!");
        }

        $info = Order::orderView(["id"=>$id,"uid"=>$user_id]);
        if(empty($info)||$info["enable"] == 0){
            return Response::wrapError('订单信息异常!');
        }

        $update = [
            "state" => $state
        ];
        if($state == 2&&$info["state"] != 1){
            return Response::wrapError("订单状态异常无法变更为发货中!");
        }else{
            $update["communicate_time"] = time();
        }

        if($state == 3&&$info["state"] != 2){
            return Response::wrapError("订单状态异常无法变更为已收货!");
        }
        $res = Order::orderEdit(["id"=>$id,"uid"=>$user_id],$update);
        if($res){
            return Response::wrapData();
        }else{
            return Response::wrapError("操作失败,请稍后重试!");
        }
    }


    public static function sampleOrderBalancePay($id,$user_id,$pay_pw){
        if(Cache::has("userAmount".$user_id)&&!empty(Cache::get("userAmount".$user_id))&&Cache::get("userAmount".$user_id)>15){
            return Response::wrapError(0,'系统结算中请稍后再试!');
        }
        $userInfo = User::userInfo(["uid"=>$user_id]);
        if($userInfo['type'] != 23){
            return Response::wrapError(0,"账户非达人用户!");
        }
        if($userInfo['enable'] == 0){
            return Response::wrapError(-200,"此账户已被禁用,如有疑问请联系平台客服!");
        }
        if(empty($userInfo["open_id"])){
            return Response::wrapError(-1,"请先授权绑定微信!");
        }
        $oInfo = SampleOrder::dataInfo(["id"=>$id,"uid"=>$user_id]);
        if(empty($oInfo)){
            return Response::wrapError(0,"订单信息异常！");
        }
        if($oInfo["state"] > 0){
            return Response::wrapError(0,"该订单不在可支付状态!");
        }
        $userAmount = UserAmount::userAmountInfo(["uid"=>$user_id]);
        if($userAmount["balance"] < $oInfo["low_price"]){
            return Response::wrapError(0,"余额不足");
        }
        if(User::encPassword($pay_pw,$userInfo["encryption"])!==$userInfo["pay_password"]){
            return Response::wrapError(0,"支付密码输入错误!");
        }
        Db::startTrans();
        try {
            $time = time();
            SampleOrder::editInfo(["id"=>$id,"uid"=>$user_id],["state"=>1,"paytime"=>$time]);
            $detailed[] = \detailed($user_id,$oInfo['low_price'],'sample_order_balance_wxpay',$userAmount['balance'],0);
            Detailed::detailedAddAll($detailed);
            UserAmount::userAmountDec(["uid"=>$user_id],"balance",$oInfo['low_price']);
            Db::commit();
            return Response::wrapData();
        }catch (\Exception $e){
            Db::rollback();
            return Response::wrapError(0,"支付失败");
        }

    }

    /*用户ID加密*/
    public static function encryptionUserNumber($user_id,$num = 8){
        $number = bcadd(bcmul($user_id,2,0),3,0);
        return str_pad($number,$num,0,STR_PAD_LEFT);
    }

    public static function createOrderNumber(){
        $orderNumber = time().mt_rand(10000,99999);
        $check = SampleOrder::dataInfo(["o_pro_num"=>$orderNumber]);
        if(!empty($check)) {
            self::createOrderNumber();
        } else {
            return $orderNumber;
        }
    }
}